package com.easy.user.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.User;
import com.easy.common.service.ILoginService;
import com.easy.common.service.ILoginService;
import com.easy.common.service.IUserService;
import com.easy.common.util.PasswordUtil;
import com.easy.common.util.SYS;
import com.easy.common.util.TokenUtil;
import com.easy.user.mapper.UserMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements ILoginService {
    @DubboReference
    private IUserService userService;

    //根据token获取用户信息
    public User logininfo(String token) {
        //token中存放的用户id
        Object id=TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        if(id==null){
            throw new RuntimeException("登录异常");
        }
        //通过用户id查询用户信息
        User user= userService.getUserById(Integer.parseInt(id.toString()));
        return user;
    }
    //用户登录验证
    @Override

    public String login(User user) {
        //登录逻辑
        //1.通过用户名查询数据库
        User result=userService.getByUsername(user.getUsername());
        if(result==null){
            throw new RuntimeException("登录异常");
        }
        //2.验证密码
        String password=user.getPassword();
        String encryptionPassword=result.getPassword();
        if(!PasswordUtil.checkPassword(password,encryptionPassword)){
            throw new RuntimeException("登录异常");
        }
        //3.返回结果token
        String token= TokenUtil.getToken(result.getId(),"user");
        return token;
    }
}
